import base64

from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import get_user_model
from django.contrib import messages

from accounts.forms import MyUserCreationForm
from app.common import is_demo
from .decorators import anonymous_required

User = get_user_model()


@anonymous_required()
def register(req):

    if req.method == 'POST':
        form = MyUserCreationForm(req.POST, use_required_attribute=False)

        if form.is_valid():
            user = form.save()

            try:
                # Auto activate users on the demo mode!
                if is_demo():
                    user.is_active = True
                    user.save()
                    messages.success(
                        req, 'Created successfully, You could login now (No need for email verification on the demo mode)!')
                else:
                    user.send_activation_mail(req)
                    messages.success(
                        req, 'Created successfully, An email message has been sent to you to activate your account!')

                return redirect('admin:login')
            except Exception as e:
                print(e)
                messages.error(
                    req, 'Something went wrong, please try again or later!!')

    else:
        form = MyUserCreationForm(use_required_attribute=False)

    context = {
        'form': form
    }

    return render(req, 'admin/auth/user/register.html', context)


def activation(req, uid64, token):
    user_id = base64.urlsafe_b64decode(uid64)
    user = get_object_or_404(User, id=user_id)

    if not (user and default_token_generator.check_token(user, token)):
        messages.warning(req, 'Invalid link!')
    else:
        user.is_active = True
        user.save()
        messages.success(
            req, 'Your account has been activated, you could login now.')

    return redirect('admin:login')


def reset_password(req):
    if req.method == 'POST':
        form = PasswordResetForm(req.POST)
        if form.is_valid():
            # TODO: send an email to the user
            email = form.cleaned_data['email']
            user_query = User.objects.filter(email=email)

            if user_query.exists():

                try:
                    user = user_query.get()
                    user.send_reset_password_mail(req)

                    messages.success(
                        req, 'An email message has been sent with password reset instructions.')
                except Exception as e:
                    print(e)
                    messages.error(
                        req, 'Something went wrong, please try again or later!!')

            else:
                messages.warning(req, "No user found with this email!")

            return redirect('reset_password')

    else:
        form = PasswordResetForm()

    context = {
        'form': form
    }

    return render(req, 'admin/auth/user/reset_password.html', context)


def set_password(req, uid64, token):
    user_id = base64.urlsafe_b64decode(uid64)
    user = get_object_or_404(User, id=user_id)

    if not (user and default_token_generator.check_token(user, token)):
        messages.warning(req, 'Invalid link!')
        return redirect('admin:login')

    form = None
    if req.method == 'POST':
        form = SetPasswordForm(user, req.POST)
        if form.is_valid():
            # Save new password
            form.save()

            messages.success(
                req, 'Your password has been successfully updated!')
            return redirect('admin:login')
        else:
            messages.warning(req, 'Invalid password!')
    else:
        form = SetPasswordForm(user)

    context = {
        'form': form
    }

    return render(req, 'admin/auth/user/set_password.html', context)
